package com.fingard.dsp.bank.directbank.lu12;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.directbank.lu11.LU11Base;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.util.ZipHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class LU12Statement extends LU11Base implements IStatement {
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();
        if ("1".equals(p_reqQrySttm.stateInsureType)) {
            return getBalanceV3Statement(p_reqQrySttm);
        } else if ("2".equals(p_reqQrySttm.stateInsureType)) {
            return getRefundFundsStatement(p_reqQrySttm);
        } else {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(p_reqQrySttm.stateInsureType + "值不为1-承保V3,2-退保，请检查ATS请求报文中'StateInsureType'字段");
            retAts.writeEnd();
            return retAts;
        }
    }

    /**
     * 退保查询
     * <p>
     * 参考接口：1.8 退保资金划拨结果文件
     * <p>
     * 文件名命名规则
     * {instid}_refundFunds_yyyyMMdd_(1).csv,
     * {instid}_refundFunds_yyyyMMdd_(1).zip
     */
    public RetAtsStatement getRefundFundsStatement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();
        String respCode = "";
        String respInfo = "";
        int totalNum = 0;

        SftpPortClient ftpPortClient = null;

        try {
            FtpSet ftpSet = bankFront.getFtpSet("statement");
            String directDir = "";
            String tmpDate = Format.Date8Format.format(p_reqQrySttm.getBusDate());
            if (ftpSet.downDir.endsWith("/")) {
                directDir = tmpDate + "refundFunds";
            } else {
                directDir = "/" + tmpDate + "/" + "refundFunds";
            }
            ftpPortClient = new SftpPortClient(ftpSet);

            // 1、查找SFTP下载目录指定文件
            String statementFileName = "";
            FtpReceiver ftpListFileReceiver = ftpPortClient.listFiles(ftpSet.downDir + directDir);
            if (!ftpListFileReceiver.isCompleted) {
                retAts.writeRespCode("-1");
                if (ConnState.FILE_NOT_EXISTS.equals(ftpListFileReceiver.connState)) {
                    retAts.writeRespInfo("SFTP服务器结果文件尚未生成!");
                } else {
                    retAts.writeRespInfo("遍历目录:" + ftpSet.downDir + directDir + "失败!");
                }
                retAts.writeEnd();
                return retAts;
            }

            List<String> fileNameList = Arrays.asList(ftpListFileReceiver.connMsg.split(","));
            Iterator<String> it = fileNameList.iterator();
            while (it.hasNext()) {
                String sftpFileName = ((String) it.next()).toString();
                statementFileName = sftpFileName;

                if (StringHelper.isNullOrEmpty(statementFileName)) {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("服务器结果文件均已处理过，无需再次处理!");
                    retAts.writeEnd();
                    return retAts;
                }

                // 2、下载退保资金划拨结果文件至本地
                String localFilePath = createTempFileDirectory() + File.separator + statementFileName;
                WriteBankLogLn2("退保资金划拨结果文件保存本地路径:" + localFilePath);

                String sftpFilePath = ftpSet.downDir + directDir + "/" + statementFileName;
                WriteBankLogLn2("待下载SFTP服务器压缩文件目录路径:" + sftpFilePath);
                FtpReceiver ftpReceiver = ftpPortClient.downloadFileFromDir(ftpSet.downDir + directDir, statementFileName, localFilePath);
                if (StringHelper.hasAnyChar(ftpReceiver.connMsg)) {
                    this.WriteBankLogLn("下载返回消息：" + ftpReceiver.connMsg);
                }

                if (ftpReceiver.isCompleted) {
                    // 5、解压文件
                    WriteBankLogLn("文件下载已完成，开始解压...");
                    String tmpLocalDir = getTempFileDirectory();
                    ZipHelper.unzipFile(localFilePath, tmpLocalDir);
                    WriteBankLogLn("文件解压至已完成.");

                    statementFileName = statementFileName.replace(".zip", "");
                    tmpLocalDir += File.separator + statementFileName;
                    File depressDir = new File(tmpLocalDir);
                    if (depressDir.exists()) {
                        String tmpStrRet = FileHelper.readFileText(tmpLocalDir + File.separator + statementFileName + ".csv", getCharset());
                        WriteBankLogLn2("解压后文件内容:\r\n" + tmpStrRet);

                        // 6、解析返回ATS
                        if (StringHelper.hasAnyChar(tmpStrRet)) {
                            respCode = "0";
                            StringReader strReader = new StringReader(tmpStrRet);
                            BufferedReader tmpReader = new BufferedReader(strReader);
                            // 投保订单号[0]
                            // 退保申请流水号[1]
                            // 退保结果保全号[2]
                            // 资金划拨请求流水号[3]
                            // 机构产品代码[4]
                            // 还款总金额[5]
                            // 还款本金[6]
                            // 还款利息[7]
                            // 还款手续费[8]
                            // 交易确认时间[9]
                            // 处理结果[10]
                            // 处理结果说明[11]
                            while (true) {
                                String eachline = tmpReader.readLine();
                                if (eachline == null) {
                                    break;
                                }
                                if (eachline.indexOf(",") > 0) {
                                    String[] detailNodes = eachline.split(",");
                                    RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();

                                    if (StringHelper.hasAnyChar(detailNodes[1].replace("\"", ""))) {
                                        totalNum++;
                                        tmpRetDetail.srcNote = detailNodes[0].replace("\"", "");
                                        tmpRetDetail.refundSeq = detailNodes[1].replace("\"", "");
                                        tmpRetDetail.askNumber = detailNodes[3].replace("\"", "");
                                        tmpRetDetail.summary = detailNodes[4].replace("\"", "");
                                        tmpRetDetail.amount = detailNodes[5].replace("\"", "");
                                        tmpRetDetail.busTime = Format.DateTime14Format.format(Format.DateTime14Format3.parse(detailNodes[9].replace("\"", "")));
                                        //0: 成功
                                        //1: 失败
                                        //2：交易未结束，处理中
                                        //-1：异常数据，订单号不存在
                                        String state = detailNodes[10].replace("\"", "");
                                        if ("0".equals(state)) {
                                            tmpRetDetail.transState = TransState.Success;
                                        } else if ("2".equals(state)) {
                                            tmpRetDetail.transState = TransState.Paying;
                                        } else {
                                            tmpRetDetail.transState = TransState.Fail;
                                        }
                                        tmpRetDetail.transMsg = detailNodes[11].replace("\"", "");
                                        tmpRetDetail.billType = "1";
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
                            }
                        } else {
                            respCode = "0";
                            respInfo = "解压后退保资金划拨结果文件内容为空";
                        }
                    } else {
                        respCode = "-1";
                        respInfo = "解压后目录[" + tmpLocalDir + "]不存在";
                    }
                } else {
                    respCode = "-1";
                    respInfo = "退保资金划拨结果文件下载失败:" + ftpReceiver.connMsg;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            respCode = "-1";
            respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (ftpPortClient != null) {
                try {
                    ftpPortClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                    WriteBankLogLn(e);
                }
            }
        }
        retAts.writeTotalNum(String.valueOf(totalNum));
        retAts.writeRespCode(respCode);
        retAts.writeRespInfo(respInfo);
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 参考文档：陆金所保险系统外部对接文档
     * 参考章节：1.10.承保资金对账文件V3
     * <p>
     * 文件名命名规则
     * {instid}_accountBalanceV3_yyyyMMdd_(1).csv,
     * {instid}_accountBalanceV3_yyyyMMdd_(1).zip
     */
    public RetAtsStatement getBalanceV3Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();
        String respCode = "";
        String respInfo = "";
        int totalNum = 0;
        SftpPortClient ftpPortClient = null;

        try {
            FtpSet ftpSet = bankFront.getFtpSet("statement");
            String directDir = "";
            String tmpDate = Format.Date8Format.format(p_reqQrySttm.getBusDate());
            if (ftpSet.downDir.endsWith("/")) {
                directDir = tmpDate + "accountBalanceV3";
            } else {
                directDir = "/" + tmpDate + "/" + "accountBalanceV3";
            }
            ftpPortClient = new SftpPortClient(ftpSet);

            // 1、查找SFTP下载目录指定文件
            String statementFileName = "";
            FtpReceiver ftpListFileReceiver = ftpPortClient.listFiles(ftpSet.downDir + directDir);
            if (!ftpListFileReceiver.isCompleted) {
                retAts.writeRespCode("-1");
                if (ConnState.FILE_NOT_EXISTS.equals(ftpListFileReceiver.connState)) {
                    retAts.writeRespInfo("SFTP服务器结果文件尚未生成!");
                } else {
                    retAts.writeRespInfo("遍历目录:" + ftpSet.downDir + directDir + "失败!");
                }
                retAts.writeEnd();
                return retAts;
            }

            List<String> fileNameList = Arrays.asList(ftpListFileReceiver.connMsg.split(","));
            Iterator<String> it = fileNameList.iterator();
            while (it.hasNext()) {
                String sftpFileName = ((String) it.next()).toString();
                statementFileName = sftpFileName;

                if (StringHelper.isNullOrEmpty(statementFileName)) {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("服务器结果文件均已处理过，无需再次处理!");
                    retAts.writeEnd();
                    return retAts;
                }

                // 2、下载承保资金对账文件至本地
                String localFilePath = createTempFileDirectory() + File.separator + statementFileName;
                WriteBankLogLn2("承保资金对账文件保存本地路径:" + localFilePath);

                String sftpFilePath = ftpSet.downDir + directDir + "/" + statementFileName;
                WriteBankLogLn2("待下载SFTP服务器压缩文件目录路径:" + sftpFilePath);
                FtpReceiver ftpReceiver = ftpPortClient.downloadFileFromDir(ftpSet.downDir + directDir, statementFileName, localFilePath);
                if (StringHelper.hasAnyChar(ftpReceiver.connMsg)) {
                    this.WriteBankLogLn("下载返回消息：" + ftpReceiver.connMsg);
                }

                if (ftpReceiver.isCompleted) {
                    // 5、解压文件
                    WriteBankLogLn("文件下载已完成，开始解压...");
                    String tmpLocalDir = getTempFileDirectory();
                    ZipHelper.unzipFile(localFilePath, tmpLocalDir);
                    WriteBankLogLn("文件解压至已完成.");

                    statementFileName = statementFileName.replace(".zip", "");
                    tmpLocalDir += File.separator + statementFileName;
                    File depressDir = new File(tmpLocalDir);
                    if (depressDir.exists()) {
                        String tmpStrRet = FileHelper.readFileText(tmpLocalDir + File.separator + statementFileName + ".csv", getCharset());
                        WriteBankLogLn2("解压后文件内容:\r\n" + tmpStrRet);

                        // 6、解析返回ATS
                        if (StringHelper.hasAnyChar(tmpStrRet)) {
                            respCode = "0";
                            StringReader strReader = new StringReader(tmpStrRet);
                            BufferedReader tmpReader = new BufferedReader(strReader);
                            // 投保人身份证号码[0]
                            // 投保人的平安付帐户[1]
                            // 投保订单号[2]
                            // 客户姓名[3]
                            // 记账时间[4]
                            // 资金流水号[5]
                            // 商户订单号[6]
                            // 交易完成时间[7]
                            // 交易类型[8]
                            // 场景[9]
                            // 支出[10]
                            // 收入[11]
                            // 账户余额[12]
                            // 账户类型[13]
                            // 商户号[14]
                            while (true) {
                                String eachline = tmpReader.readLine();
                                if (eachline == null) {
                                    break;
                                }
                                if (eachline.indexOf(",") > 0) {
                                    String[] detailNodes = eachline.split(",");
                                    RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();

                                    if (StringHelper.hasAnyChar(detailNodes[1].replace("\"", ""))) {
                                        totalNum++;
                                        tmpRetDetail.askNumber = detailNodes[5].replace("\"", "");
                                        tmpRetDetail.busType = detailNodes[8].replace("\"", "");
                                        tmpRetDetail.busTime = Format.DateTime14Format.format(Format.DateTime14Format3.parse(detailNodes[7].replace("\"", "")));
                                        String amount = StringHelper.amountDivide1000000(detailNodes[10].replace("\"", ""));
                                        if (Double.parseDouble(amount) <= 0) {
                                            amount = StringHelper.amountDivide1000000(detailNodes[11].replace("\"", ""));
                                            tmpRetDetail.billType = "2";
                                        } else {
                                            tmpRetDetail.billType = "1";
                                        }
                                        tmpRetDetail.amount = amount;
                                        tmpRetDetail.bkSeq = detailNodes[6].replace("\"", "");
                                        tmpRetDetail.transState = TransState.Success;
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
                            }
                        } else {
                            respCode = "0";
                            respInfo = "解压后承保资金对账文件内容为空";
                        }
                    } else {
                        respCode = "-1";
                        respInfo = "解压后目录[" + tmpLocalDir + "]不存在";
                    }
                } else {
                    respCode = "-1";
                    respInfo = "承保资金对账文件下载失败:" + ftpReceiver.connMsg;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            respCode = "-1";
            respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (ftpPortClient != null) {
                try {
                    ftpPortClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                    WriteBankLogLn(e);
                }
            }
        }
        retAts.writeTotalNum(String.valueOf(totalNum));
        retAts.writeRespCode(respCode);
        retAts.writeRespInfo(respInfo);
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 参考文档：陆金所保险系统外部对接文档
     * 参考章节：1.11.承保资金对账文件V4
     * <p>
     * 文件名命名规则
     * {instid}_accountBalanceV4_yyyyMMdd_(1).csv,
     * {instid}_accountBalanceV4_yyyyMMdd_(1).zip
     */
    public RetAtsStatement getBalanceV4Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();
        String respCode = "";
        String respInfo = "";
        int totalNum = 0;

        SftpPortClient ftpPortClient = null;
        try {
            FtpSet ftpSet = bankFront.getFtpSet("statement");
            String directDir = "";
            String tmpDate = Format.Date8Format.format(p_reqQrySttm.getBusDate());
            if (ftpSet.downDir.endsWith("/")) {
                directDir = tmpDate + "accountBalanceV4";
            } else {
                directDir = "/" + tmpDate + "/" + "accountBalanceV4";
            }
            ftpPortClient = new SftpPortClient(ftpSet);

            // 1、查找SFTP下载目录指定文件
            String statementFileName = "";
            FtpReceiver ftpListFileReceiver = ftpPortClient.listFiles(ftpSet.downDir + directDir);
            if (!ftpListFileReceiver.isCompleted) {
                retAts.writeRespCode("-1");
                if (ConnState.FILE_NOT_EXISTS.equals(ftpListFileReceiver.connState)) {
                    retAts.writeRespInfo("SFTP服务器结果文件尚未生成!");
                } else {
                    retAts.writeRespInfo("遍历目录:" + ftpSet.downDir + directDir + "失败!");
                }
                retAts.writeEnd();
                return retAts;
            }

            List<String> fileNameList = Arrays.asList(ftpListFileReceiver.connMsg.split(","));
            Iterator<String> it = fileNameList.iterator();
            while (it.hasNext()) {
                String sftpFileName = ((String) it.next()).toString();
                statementFileName = sftpFileName;

                if (StringHelper.isNullOrEmpty(statementFileName)) {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("服务器结果文件均已处理过，无需再次处理!");
                    retAts.writeEnd();
                    return retAts;
                }

                // 2、下载承保资金对账文件至本地
                String localFilePath = createTempFileDirectory() + File.separator + statementFileName;
                WriteBankLogLn2("承保资金对账文件保存本地路径:" + localFilePath);

                String sftpFilePath = ftpSet.downDir + directDir + "/" + statementFileName;
                WriteBankLogLn2("待下载SFTP服务器压缩文件目录路径:" + sftpFilePath);
                FtpReceiver ftpReceiver = ftpPortClient.downloadFileFromDir(ftpSet.downDir + directDir, statementFileName, localFilePath);
                if (StringHelper.hasAnyChar(ftpReceiver.connMsg)) {
                    this.WriteBankLogLn("下载返回消息：" + ftpReceiver.connMsg);
                }

                if (ftpReceiver.isCompleted) {
                    // 5、解压文件
                    WriteBankLogLn("文件下载已完成，开始解压...");
                    String tmpLocalDir = getTempFileDirectory();
                    ZipHelper.unzipFile(localFilePath, tmpLocalDir);
                    WriteBankLogLn("文件解压至已完成.");

                    statementFileName = statementFileName.replace(".zip", "");
                    tmpLocalDir += File.separator + statementFileName;
                    File depressDir = new File(tmpLocalDir);
                    if (depressDir.exists()) {
                        String tmpStrRet = FileHelper.readFileText(tmpLocalDir + File.separator + statementFileName + ".csv", getCharset());
                        WriteBankLogLn2("解压后文件内容:\r\n" + tmpStrRet);

                        // 6、解析返回ATS
                        if (StringHelper.hasAnyChar(tmpStrRet)) {
                            respCode = "0";
                            StringReader strReader = new StringReader(tmpStrRet);
                            BufferedReader tmpReader = new BufferedReader(strReader);
                            // 投保人身份证号码[0]
                            // 投保人的平安付帐户[1]
                            // 投保订单号[2]
                            // 客户姓名[3]
                            // 记账时间[4]
                            // 资金流水号[5]
                            // 商户订单号[6]
                            // 交易完成时间[7]
                            // 交易类型[8]
                            // 场景[9]
                            // 支出[10]
                            // 收入[11]
                            // 账户余额[12]
                            // 账户类型[13]
                            // 商户号[14]
                            // 追加投资订单号[15]
                            // 类型[16]
                            while (true) {
                                String eachline = tmpReader.readLine();
                                if (eachline == null) {
                                    break;
                                }
                                if (eachline.indexOf(",") > 0) {
                                    String[] detailNodes = eachline.split(",");
                                    RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();

                                    if (StringHelper.hasAnyChar(detailNodes[1].replace("\"", ""))) {
                                        totalNum++;
                                        tmpRetDetail.askNumber = detailNodes[5].replace("\"", "");
                                        tmpRetDetail.busType = detailNodes[8].replace("\"", "");
                                        tmpRetDetail.busTime = Format.DateTime14Format.format(Format.DateTime14Format3.parse(detailNodes[7].replace("\"", "")));
                                        String amount = StringHelper.amountDivide1000000(detailNodes[10].replace("\"", ""));
                                        if (Double.parseDouble(amount) <= 0) {
                                            amount = StringHelper.amountDivide1000000(detailNodes[11].replace("\"", ""));
                                            tmpRetDetail.billType = "2";
                                        } else {
                                            tmpRetDetail.billType = "1";
                                        }
                                        tmpRetDetail.amount = amount;

                                        tmpRetDetail.transState = TransState.Success;
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
                            }
                        } else {
                            respCode = "0";
                            respInfo = "解压后承保资金对账文件内容为空";
                        }
                    } else {
                        respCode = "-1";
                        respInfo = "解压后目录[" + tmpLocalDir + "]不存在";
                    }
                } else {
                    respCode = "-1";
                    respInfo = "承保资金对账文件下载失败:" + ftpReceiver.connMsg;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            respCode = "-1";
            respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (ftpPortClient != null) {
                try {
                    ftpPortClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                    WriteBankLogLn(e);
                }
            }
        }
        retAts.writeTotalNum(String.valueOf(totalNum));
        retAts.writeRespCode(respCode);
        retAts.writeRespInfo(respInfo);
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 参考文档：陆金所保险系统外部对接文档
     * 参考章节：1.12.承保失败资金对账文件
     * <p>
     * 文件名命名规则
     * {instid}_policyFailFunds_yyyyMMdd_(1).csv,
     * {instid}_policyFailFunds_yyyyMMdd_(1).zip
     */
    public RetAtsStatement getFailFundsStatement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();
        String respCode = "";
        String respInfo = "";
        int totalNum = 0;
        SftpPortClient ftpPortClient = null;

        try {
            FtpSet ftpSet = bankFront.getFtpSet("statement");
            String directDir = "";
            String tmpDate = Format.Date8Format.format(p_reqQrySttm.getBusDate());
            if (ftpSet.downDir.endsWith("/")) {
                directDir = tmpDate + "policyFailFunds";
            } else {
                directDir = "/" + tmpDate + "/" + "policyFailFunds";
            }
            ftpPortClient = new SftpPortClient(ftpSet);

            // 1、查找SFTP下载目录指定文件
            String statementFileName = "";
            FtpReceiver ftpListFileReceiver = ftpPortClient.listFiles(ftpSet.downDir + directDir);
            if (!ftpListFileReceiver.isCompleted) {
                retAts.writeRespCode("-1");
                if (ConnState.FILE_NOT_EXISTS.equals(ftpListFileReceiver.connState)) {
                    retAts.writeRespInfo("SFTP服务器结果文件尚未生成!");
                } else {
                    retAts.writeRespInfo("遍历目录:" + ftpSet.downDir + directDir + "失败!");
                }
                retAts.writeEnd();
                return retAts;
            }

            List<String> fileNameList = Arrays.asList(ftpListFileReceiver.connMsg.split(","));
            Iterator<String> it = fileNameList.iterator();
            while (it.hasNext()) {
                String sftpFileName = ((String) it.next()).toString();
                statementFileName = sftpFileName;

                if (StringHelper.isNullOrEmpty(statementFileName)) {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("服务器结果文件均已处理过，无需再次处理!");
                    retAts.writeEnd();
                    return retAts;
                }
                // 2、下载承保资金对账文件至本地
                String localFilePath = createTempFileDirectory() + File.separator + statementFileName;
                WriteBankLogLn2("承保失败资金对账文件保存本地路径:" + localFilePath);

                String sftpFilePath = ftpSet.downDir + directDir + "/" + statementFileName;
                WriteBankLogLn2("待下载SFTP服务器压缩文件目录路径:" + sftpFilePath);
                FtpReceiver ftpReceiver = ftpPortClient.downloadFileFromDir(ftpSet.downDir + directDir, statementFileName, localFilePath);
                if (StringHelper.hasAnyChar(ftpReceiver.connMsg)) {
                    this.WriteBankLogLn("下载返回消息：" + ftpReceiver.connMsg);
                }

                if (ftpReceiver.isCompleted) {
                    // 5、解压文件
                    WriteBankLogLn("文件下载已完成，开始解压...");
                    String tmpLocalDir = getTempFileDirectory();
                    ZipHelper.unzipFile(localFilePath, tmpLocalDir);
                    WriteBankLogLn("文件解压至已完成.");

                    statementFileName = statementFileName.replace(".zip", "");
                    tmpLocalDir += File.separator + statementFileName;
                    File depressDir = new File(tmpLocalDir);
                    if (depressDir.exists()) {
                        String tmpStrRet = FileHelper.readFileText(tmpLocalDir + File.separator + statementFileName + ".csv", getCharset());
                        WriteBankLogLn2("解压后文件内容:\r\n" + tmpStrRet);

                        // 6、解析返回ATS
                        if (StringHelper.hasAnyChar(tmpStrRet)) {
                            respCode = "0";
                            StringReader strReader = new StringReader(tmpStrRet);
                            BufferedReader tmpReader = new BufferedReader(strReader);
                            //投保订单号[0]
                            //机构产品代码[1]
                            //退款金额[2]
                            //平安付退款划账时间[3]
                            //平安付退款划账流水号[4]
                            //客户姓名[5]
                            //客户商户号[6]
                            //客户投保资金流水号[7]
                            //客户投保资金划拨时间[8]
                            //处理结果[9]
                            //结果说明[10]
                            //扩展字段[11]
                            while (true) {
                                String eachline = tmpReader.readLine();
                                if (eachline == null) {
                                    break;
                                }
                                if (eachline.indexOf(",") > 0) {
                                    String[] detailNodes = eachline.split(",");
                                    RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();

                                    if (StringHelper.hasAnyChar(detailNodes[1].replace("\"", ""))) {
                                        totalNum++;
                                        tmpRetDetail.askNumber = detailNodes[7].replace("\"", "");
                                        tmpRetDetail.busType = detailNodes[8].replace("\"", "");
                                        tmpRetDetail.busTime = Format.DateTime14Format.format(Format.DateTime14Format3.parse(detailNodes[7].replace("\"", "")));
                                        tmpRetDetail.amount = detailNodes[2].replace("\"", "");
                                        String transState = detailNodes[9].replace("\"", "");
                                        if ("1".equals(transState)) {
                                            tmpRetDetail.transState = TransState.Success;
                                        } else if ("0".equals(transState)) {
                                            tmpRetDetail.transState = TransState.Fail;
                                        } else if ("2".equals(transState)) {
                                            tmpRetDetail.transState = TransState.Paying;
                                        }
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
                            }
                        } else {
                            respCode = "0";
                            respInfo = "解压后承保失败资金对账文件内容为空";
                        }
                    } else {
                        respCode = "-1";
                        respInfo = "解压后目录[" + tmpLocalDir + "]不存在";
                    }
                } else {
                    respCode = "-1";
                    respInfo = "承保失败资金对账文件下载失败:" + ftpReceiver.connMsg;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            respCode = "-1";
            respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (ftpPortClient != null) {
                try {
                    ftpPortClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                    WriteBankLogLn(e);
                }
            }
        }
        retAts.writeTotalNum(String.valueOf(totalNum));
        retAts.writeRespCode(respCode);
        retAts.writeRespInfo(respInfo);
        retAts.writeEnd();
        return retAts;
    }

}
